export default class Snake{
    // 表示蛇头的元素
    head: HTMLElement;

    // 蛇身体，包含头
    bodies: HTMLCollection

    // 获取 蛇的容器
    element: HTMLElement;

    constructor(){
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = this.element.getElementsByTagName('div')
    }

    // 获取 蛇头 坐标
    get X (){
        return this.head.offsetLeft;
    }

    get Y (){
        return this.head.offsetTop;
    }

    // 设置 蛇头坐标
    set X (value: number){
        if(this.X === value){
            return
        }
        if(value > 290 || value < 0){
            throw new Error('蛇撞墙了！')
        }

        if( this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value ){
            // console.log('水平方向掉头了')
            // 继续按照原来方向运动
            if(value > this.X){
                // 蛇向右走，此时掉头，继续向左走
                value = this.X - 10;
            }else{
                value = this.X + 10
            }
        }
        
        this.moveBody()
        this.head.style.left = value + 'px'
        this.checkHeaderSameBody()
    }

    set Y (value: number){
        if(this.Y === value){
            return
        }
        if(value > 290 || value < 0){
            throw new Error('蛇撞墙了！')
        }

        if( this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value ){
            // console.log('垂直方向掉头了')
             // 继续按照原来方向运动
             if(value > this.Y){
                // 蛇向右走，此时掉头，继续向左走
                value = this.Y - 10;
            }else{
                value = this.Y + 10
            }
        }

        this.moveBody()
        this.head.style.top = value + 'px'
        this.checkHeaderSameBody()
    }

    // 吃到食物，蛇身体增加一部分
    addBody(){
        this.element.insertAdjacentHTML('beforeend','<div></div>')
    }

    // 蛇 身体移动方法
    moveBody(){
        // 将 后边的坐标设置为 前边身体的位置
        for(let i = this.bodies.length -1 ; i > 0 ; i-- ){
            let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
            // 设置值到 对应身体上
            (this.bodies[i] as HTMLElement).style.left = X + "px";
            (this.bodies[i] as HTMLElement).style.top = Y + "px";

        }
    }

    // 蛇是否撞到自己身体了
    checkHeaderSameBody(){
        for(let i = 1; i < this.bodies.length; i++){
            let bd = this.bodies[i] as HTMLElement;
            if( this.X === bd.offsetLeft && this.Y === bd.offsetTop){
                throw new Error('蛇撞到自己了！')
            }
        }
       
    }
}